import 'dart:convert';

import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

class SelectedLocationController extends GetxController {
  // 输入的作业地点
  String ticketAddress = '';

  // 经纬度
  Map<String, double> laAndLon = {};

  late InAppWebViewController inAppWebViewController;

  /// &noScale=true : 是否全屏
  URLRequest url = URLRequest(url: Uri.parse('${Interface.mapUrl}/#/?func=plotting&onlyPlot=true&noScale=true'));

  /// webview加载完成后
  onWebViewCreated(InAppWebViewController controller) async {
    inAppWebViewController = controller;

    // 判断地形和瓦片地址是否为空
    if (Interface.terrainUrl == '') {
      AppToast.showWarning('地形为空', duration: const Duration(seconds: 3));
    }
    if (Interface.tilesetUrl == '') {
      AppToast.showWarning('瓦片为空', duration: const Duration(seconds: 3));
    }

    // 先加载地形
    await _loadTerrain(Interface.terrainUrl);
    // 加载瓦片
    await _loadTileset(Interface.tilesetUrl);
    // 加载图标
    _loadIcon();
  }

  // 加载按钮图标
  _loadIcon() async {
    await Future.delayed(const Duration(seconds: 1));
    _sendMessage({
      'type': 'setToolLayout',
      'data': {
        'include': ['图标点'], // 只能启用一个
        'operTool': {
          'include': ['完成'],
          'style': {'fontSize': '20px'}
        },
        'rename': {'图标点': '作业地点'} // 重名
      }
    });
  }

  // 加载地形地址
  _loadTerrain(String url) async {
    final data = {
      'type': 'Terrain',
      'data': {
        'url': url,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 加载瓦片地址
  /// [tileUrl] 暂时写死，后面要动态获取
  _loadTileset(String tileUrl) async {
    final data = {
      'type': 'Tileset',
      'data': {
        'url': tileUrl,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);

    // inAppWebViewController.evaluateJavascript(source: 'handleLayoutReset()');
    // _sendMessage(data);
    // _initPoint();
    inAppWebViewController.addJavaScriptHandler(
        handlerName: 'receiveMsg',
        callback: (List<dynamic> args) {
          AppLogger.log(args.toString());
          final json = jsonDecode(args[0].toString());
          double longitude = 0;
          double latitude = 0;
          try {
            if (json['positions'] != null && json['positions'] is List) {
              final List data = json['positions'] as List;
              if (data.length > 1) {
                longitude = data[0] as double;
                latitude = data[1] as double;
              }
            }
          } catch (_) {}
          laAndLon = {'longitude': longitude, 'latitude': latitude};
          if (ticketAddress.isNotEmpty) {
            if (laAndLon.isNotEmpty) {
              exit();
            } else {
              AppToast.showWarning('请选取经纬度');
            }
          } else {
            AppToast.showWarning('请输入地点名称');
          }
        });
  }

  /// 发送消息
  Future<void> _sendMessage(data) async {
    await inAppWebViewController.postWebMessage(message: WebMessage(data: jsonEncode(data)));
  }

  void exit() {
    Get.back(result: {'laAndLon': laAndLon, 'ticketAddress': ticketAddress});
  }

  @override
  void onReady() {
    super.onInit();
  }
}
